﻿using System;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web.Mvc;
using System.Xml.Linq;
using Senparc.Weixin.BrowserUtility;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.TenPayLibV3;
using ZXing;
using ZXing.Common;
using Senparc.Weixin.MP;
using Senparc.Weixin;
using System.Collections.Generic;
using WeixinPayService.Models;
using WeixinPayService.Service;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.CommonAPIs;

namespace Superstore.Vender.Controllers
{
	public class TenPayV3Controller : Controller
	{
		private static TenPayV3Info _tenPayV3Info;

		public static TenPayV3Info TenPayV3Info
		{
			get
			{
                if (_tenPayV3Info == null)
                {
                    _tenPayV3Info = TenPayInfoRegister.Register();
                }
				return _tenPayV3Info;
			}
		}

		/// <summary>
        /// 获取用户的OpenId 并跳转至支付页
		/// </summary>
        /// <param name="attachInfo">自定义信息(提交给微信 微信支付完成后 微信原样返回)</param>
		/// <param name="orderNumber">货机订单号</param>
		/// <param name="returnUrl">调起公众号支付的url</param>
		/// <returns></returns>
		public ActionResult Index(string attachInfo, string orderNumber, string returnUrl = "")
		{
            //加上 showwxpaytitle=1 页面title会有“微信安全支付”的文字
            returnUrl = "http://wxv.superstore5000.com/TenPayV3/JsApi";
            return Redirect(WeixinPay.OAuthReturnUrl(attachInfo, orderNumber, returnUrl));
		}

		#region JsApi支付
        public BrandWCPay GetBrandWCPayInfo(string code, string state)
        {
            BrandWCPay model = new BrandWCPay();
            try
            {
                model = WeixinPay.GetBrandWCPay(code, state, Request.UserHostAddress);

            }
            catch (Exception ex)
            {
                FileStream fileStream = System.IO.File.OpenWrite(Server.MapPath("~/2.txt"));
                fileStream.Write(Encoding.Default.GetBytes(ex.ToString() + code + state), 0, Encoding.Default.GetByteCount(ex.ToString() + code + state));
                fileStream.Close();
            }
            return model;
        }
        /// <summary>
        /// 调起微信支付的页面
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
		public ActionResult JsApi(string code, string state)
		{
			BrandWCPay model = new BrandWCPay();
			model = GetBrandWCPayInfo(code, state);
			//预下单成功
			if (model.errorCode == "0000")
			{
				ViewBag.appId = model.appId;
				ViewBag.timeStamp = model.timeStamp;
				ViewBag.nonceStr = model.nonceStr;
				ViewBag.package = model.package;
				ViewBag.paySign = model.paySign;
				return View();
			}
			else
			{
				ViewBag.errorDesc = model.errorDesc;
				return View();
			}
		}

        /// <summary>
        /// 订单回调页面
        /// </summary>
        public ActionResult PayNotifyUrl()
        {

            ResponseHandler resHandler = new ResponseHandler(null);
            int orderStatus = WeixinPay.PayNotifyCode(resHandler);
            string xml = "";
            //商家信息 订单号 订单总费用
            string accId = "", orderNumber = "", total_fee = "";
            if (orderStatus == 1)
            {
                //交易成功
                accId = resHandler.GetParameter("attach");
                orderNumber = resHandler.GetParameter("out_trade_no");
                total_fee = resHandler.GetParameter("total_fee");


                xml = "<xml>"
                    + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>"
                    +"</xml>";
            }
            else if (orderStatus == 2)
            {
                //交易失败
            }
            else if (orderStatus == 3)
            {
                //通信失败
            }
            else if (orderStatus == 4)
            {
                //非微信支付订单
            }

            #region 测试记录用
            string newxml = string.Format(@"<xml>
	    <return_code><![CDATA[{0}]]></return_code>
	    <return_msg><![CDATA[{1}]]></return_msg>
	    <appid><![CDATA[{2}]]></appid>
	    <mch_id><![CDATA[{3}]]></mch_id>
	    <nonce_str><![CDATA[{4}]]></nonce_str>
	    <sign><![CDATA[{5}]]></sign>
	    <result_code><![CDATA[{6}]]></result_code>
	    <prepay_id><![CDATA[{7}]]></prepay_id>
	    <trade_type><![CDATA[{8}]]></trade_type>
		<accId>![CDATA[{9}]]</accId>
		<out_trade_no>![CDATA[{10}]]</out_trade_no>
		<total_fee>![CDATA[{11}]]</total_fee>
	</xml>",
       resHandler.GetParameter("return_code"),
       resHandler.GetParameter("return_msg"),
       resHandler.GetParameter("appid"),
       resHandler.GetParameter("mch_id"),
       resHandler.GetParameter("nonce_str"),
       resHandler.GetParameter("sign"),
       resHandler.GetParameter("result_code"),
       resHandler.GetParameter("prepay_id"),
       resHandler.GetParameter("trade_type"),
       accId,
       resHandler.GetParameter("out_trade_no"),
       resHandler.GetParameter("total_fee"));

            FileStream fileStream = System.IO.File.OpenWrite(Server.MapPath("~/1.txt"));
            fileStream.Write(Encoding.Default.GetBytes(newxml), 0, Encoding.Default.GetByteCount(newxml));
            fileStream.Close();
            #endregion

            return Content(xml, "text/xml");
        }

		#endregion

	}
}